package com.falcon.modules.controller;

import com.falcon.modules.domain.dto.User;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Map;

@Controller
@Slf4j
public class LoginController {
    public static final String KAPTCHA_NAME = "kaptcha";
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @GetMapping("/login")
    public String login(Map<String, Object> model, HttpServletRequest httpServletRequest) {
//        model.put("message", httpServletRequest.getSession().getId() + "====" + httpServletRequest.getSession().getAttribute("vrifyCode"));
        return "login";
    }
    @RequestMapping(value = "loginValid",method = RequestMethod.POST)
    public String loginValid(Model model,
                              HttpServletRequest request,
                              User user,
                              @RequestParam(required = false, defaultValue = "false") boolean remembered) {
        try {
            Subject curUser = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(), user.getPwd());
            String sessionKaptcha = (String) request.getSession().getAttribute(KAPTCHA_NAME);

            String requestKaptcha = request.getParameter(KAPTCHA_NAME);

            log.info("session kaptcha:{},request kaptcha:{}", sessionKaptcha, requestKaptcha);

//            if (StringUtils.isEmpty(user.getAccount())) {
//                model.addAttribute("message", "帐号不能为空!");
//                return "login";
//            }
//
//            if (StringUtils.isEmpty(user.getPwd())) {
//                model.addAttribute("message", "密码不能为空!");
//                return "login";
//            }
//
//            if (requestKaptcha == null) {
//                model.addAttribute("message", "验证码不能为空!");
//                return "login";
//            }
//            // 比对
//            if (sessionKaptcha == null) {
//                model.addAttribute("message", "验证码过期,请重新登录!");
//                return "login";
//            }
//            if (!requestKaptcha.equalsIgnoreCase(sessionKaptcha)) {
//                model.addAttribute("message", "验证码错误!");
//                return "login";
//            }
//
//            token.setRememberMe(remembered);
//
            try {
                curUser.login(token);
            } catch (UnknownAccountException uae) {
                model.addAttribute("message", "账号不存在!");
                return "login";
            } catch (IncorrectCredentialsException ice) {
                model.addAttribute("message", "密码错误!");
                return "login";
            } catch (LockedAccountException lae) {
                model.addAttribute("message", "账号被锁定!");
                return "login";
            } catch (AuthenticationException e) {
                model.addAttribute("message", "认证错误!");
                return "login";
            } catch (Exception e) {
                model.addAttribute("message", "未知错误,请联系管理员.");
                return "login";
            }
        } catch (Exception e) {
            log.error("登陆异常", e);
        }
        return "main";
    }

    @RequestMapping("/kaptcha")
    public void kaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = defaultKaptcha.createText();
            httpServletRequest.getSession().setAttribute(KAPTCHA_NAME, createText);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    @RequestMapping("logout")
    public String logout(){
        try {
            Subject curUser = SecurityUtils.getSubject();
            curUser.logout();
        }catch (Exception e){
            log.error("登出异常",e);
        }
        return "login";
    }

    @RequestMapping("index")
    public String index(){
        return "modules/log";
    }


    @RequestMapping("users")
    public String users(){
        return "modules/user";
    }

    @RequestMapping("roles")
    public String roles(){
        return "modules/role";
    }
}